﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using USU.MetricsMonitor.DiffParser;
using USU.MetricsMonitor.DiffProvider;
using USU.MetricsMonitor.LogParser;

namespace USU.MetricsMonitor.Metrics
{
	[Serializable]
	public class PersonalRate : MetricCollection
	{
		public PersonalRate()
		{
			MetricName = "PersonalRate";
			Description = @"Данная метрика предназначена для подсчета 
                              индивидуальной скорости разработчика: количество добавленных,
                              изменённых";

		}
        public override void Calculate(IEnumerable<RevisionInfo> parsedLog, BaseDiffProvider diffProvider, string projectName, string whiteList, string blackList)
        {
            ProjectName = projectName;

            if (Metrics == null)
                Metrics = new List<MetricBase>();

            foreach (RevisionInfo info in parsedLog)
            {
                if (info.ActionsInfo.Count(i => { return i.Kind == Kind.FILE; }) == 0) continue;

                long personalCount = 0;
                
                using (var stream = diffProvider.GetStream(info.Revision))
                    BruteDiffParser.Parse(new StreamReader(stream),
                        new DiffProcessor
                        {
                            AddedLineHandler = _ => ++personalCount
                        },
                        whiteList,
                        blackList
                    );

                MetricBase mbase = Metrics.Find((x) => { return x.Parameter == info.Author; });
                MetricUnit munit = new MetricUnit(info.Revision, info.DateTime, personalCount);

                if (mbase == null)
                {
                    Metrics.Add(mbase = new MetricBase());

                    mbase.Parameter = info.Author;
                    mbase.BeginningMetricUnit = munit;
                    mbase.BeginningDate = munit.Date;
                }

                mbase.Units.Add(munit);
                mbase.LastMetricUnit = munit;
                mbase.LastDate = munit.Date;
            }
        }
	}
}
